package com.piper.long_connection.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;

/**
 * netty5客户端
 */
public class Client {

    public static void main(String[] args) {
        //客户端
        Bootstrap bootstrap = new Bootstrap();

        //worker
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            //设置线程池
            bootstrap.group(worker);

            //设置socket工厂、
            bootstrap.channel(NioSocketChannel.class);

            //设置管道工厂
            bootstrap.handler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(new IdleStateHandler(0, 0, 5));
                    ch.pipeline().addLast(new StringDecoder());
                    ch.pipeline().addLast(new StringEncoder());
                    ch.pipeline().addLast(new ClientHandler());
                }
            });


            //绑定端口
            ChannelFuture connect = bootstrap.connect(new InetSocketAddress("127.0.0.1", 10101));
            Channel channel = connect.channel();

            System.out.println("start");

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                if (channel != null && channel.isActive()) {
                    System.out.println("请输入消息：");
                    channel.writeAndFlush(bufferedReader.readLine());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            worker.shutdownGracefully();
        }
    }
}
